import {
  isAndroid,
  isIOS,
  isTencentWebview,
  isWechat,
  getQueryParamByName,
  getBrowserType,
  reportInfoV3,
  reportInfo,
  BROWSER,
  DomUtil,
  catchGlobalError,
  uploadErrorInfo,
  onloadImage,
  getEnTitleName,
} from '@/common/js/common';
import { Base64 } from 'js-base64';
import Swiper from 'swiper/dist/js/swiper.min.js';
import 'swiper/dist/css/swiper.min.css';
import '@/common/phpFile/css/ba.css';
import '../style/download-chess-h5.scss';
import '../style/animate.css';
import ProgressBar from 'progressbar.js';
import { nameConfig } from '@theme/vm';
const SITE_NAME = process.env.SITE_NAME || '';
const imgPath = SITE_NAME + '_appdown';

catchGlobalError();

export default function (appKey: string) {
  const tyAppKey = appKey;
  const i_code: any = getQueryParamByName('i_code');
  const r_code = getQueryParamByName('r_code');
  const browserName = getBrowserType();
  // 拷过来的
  const agentDiv = document.querySelector<HTMLElement>('.agent')!;
  const qqDiv = document.querySelector<HTMLElement>('.agent_qq')!;
  const flygramDiv = document.querySelector<HTMLElement>('.agent_flygram')!;
  const qqNum = document.querySelector<HTMLElement>('.agent_qq_num')!;
  const flygramNum = document.querySelector<HTMLElement>('.agent_flygram_num')!;
  // 拷过来的

  try {
    // 设置网页标题，这样做避免微信封杀
    if (SITE_NAME === 'bw') {
      document.title = nameConfig.welComeText;
    } else {
      if (i_code) {
        document.title =
          getEnTitleName(nameConfig?.brand) +
          Base64.decode(`5qyi6L+O5L2/55So${nameConfig.brandName}QXBw`) +
          i_code;
      } else if (r_code) {
        document.title =
          getEnTitleName(nameConfig?.brand) +
          Base64.decode(`5qyi6L+O5L2/55So${nameConfig.brandName}QXBw`) +
          r_code;
      } else {
        document.title =
          getEnTitleName(nameConfig?.brand) +
          Base64.decode(`5qyi6L+O5L2/55So${nameConfig.brandName}QXBw`);
      }
    }
  } catch (error) {
    uploadErrorInfo('game.setTitle', error, false);
  }

  try {
    // 如果是非移动端用户
    if (!isIOS() && !isAndroid()) {
      let subfix = '';

      if (i_code) {
        subfix = '?i_code=' + i_code;
      } else if (r_code) {
        subfix = '?r_code=' + r_code;
      }
      // 跳转至PC端页面
      window.location.href = 'download_chess.html' + subfix;
      return;
    }
  } catch (error) {
    uploadErrorInfo('game.forward', error, false);
    return;
  }

  const mobileprovision = './';

  // 拷过来的
  function initTySCM() {
    try {
      // 初始化TySCM
      const qpSCM = window.TySCM({
        appKey: tyAppKey,
        onready: (o) => {
          const downloadPanel =
            document.querySelector<HTMLElement>('#download');
          if (downloadPanel) {
            DomUtil.show(downloadPanel);
            const installBtn = document.querySelector<HTMLElement>('#install');
            const cirleProcess =
              document.querySelector<HTMLElement>('#cirle-process')!;
            if (installBtn) {
              if (isIOS()) {
                document.querySelector('#text-circle').className +=
                  ' ios_circle_class';
              }
              installBtn.addEventListener('click', function () {
                const trustElem =
                  document.querySelector<HTMLElement>('#trust')!;
                if (installBtn.innerText === '下载完成') {
                  return;
                }
                try {
                  installBtn.setAttribute('disabled', 'disabled');

                  // 执行第三方下载安装包方法;
                  o.wakeupOrInstall(function (
                    profileUrl: string | undefined
                  ): void {
                    if (profileUrl) {
                      const trustBtn =
                        document.querySelector<HTMLElement>('#trust');

                      if (trustBtn) {
                        DomUtil.show(trustBtn);

                        trustBtn.addEventListener('click', function () {
                          try {
                            const browserName = getBrowserType();

                            if (browserName === BROWSER.SAFARI) {
                              reportInfoV3('ios_yabo_trust_click');
                              reportInfoV3('ios_yabo_trust_uv');
                              window.location.href = profileUrl;
                            } else {
                              const wrapPanel =
                                document.querySelector<HTMLElement>(
                                  '.modal_wrap'
                                );

                              if (wrapPanel) {
                                DomUtil.show(wrapPanel);
                              }
                            }
                          } catch (error) {
                            uploadErrorInfo(
                              'game.trustBtn.click',
                              error,
                              false
                            );
                          }
                        });
                      }
                    }
                  });

                  if (isIOS()) {
                    reportInfoV3('ios_yabo_download_click');
                    // installBtn.innerText = '正在下载 0%';
                    installBtn.innerText = '一键信任';

                    DomUtil.hide(installBtn);
                    DomUtil.show(trustElem);
                    DomUtil.show(cirleProcess);
                    setTimeout(function () {
                      downloadProgress();
                    }, 50);
                  } else {
                    DomUtil.show(cirleProcess);
                    setTimeout(function () {
                      downloadProgress();
                    }, 50);
                    installBtn.innerText = nameConfig.nowText + '...';
                    reportInfoV3('android_yabo_download_click');
                    // DomUtil.toggleClass(installBtn, 'btn-loading');

                    setTimeout(function () {
                      // DomUtil.toggleClass(installBtn, 'btn-loading');
                      installBtn.innerText = '立即下载';
                      installBtn.removeAttribute('disabled');
                    }, 20000);
                  }
                } catch (error) {
                  uploadErrorInfo('game.installBtn.click', error, false);
                }
              });
            }
          }
        },
      });
      qpSCM.toSuperSign();
    } catch (error) {
      uploadErrorInfo('game.initTySCM', error, false);
    }
  }
  // 拷过来的

  initTySCM();
  showDownloadTips();
  showICode();
  initOther();

  isTencentWebview() ? displayViewGuide() : '';

  /**
   * displayViewGuide 引导
   */
  function displayViewGuide() {
    try {
      const tmpl =
        '<div class="app-guide-mask"><div class="blur"></div><span class="guide-img"></span></div>';

      const appGuideMask = DomUtil.create(tmpl);

      if (appGuideMask) {
        document.body.appendChild(appGuideMask);

        appGuideMask.addEventListener('touchmove', function (event: Event) {
          event.preventDefault();
        });

        appGuideMask.addEventListener('click', function () {
          DomUtil.remove(appGuideMask);
        });
      }
    } catch (error) {
      uploadErrorInfo('game.displayViewGuide', error, false);
    }
  }

  function initOther() {
    try {
      // const iphoneBrand = document.querySelector('#iphoneBrand')!;
      const installTutorial =
        document.querySelector<HTMLElement>('#installTutorial');
      const iosInstallInfo =
        document.querySelector<HTMLElement>('#iosInstallInfo');
      const torialRegion = document.querySelector<HTMLElement>('#torialRegion');
      const downloadWrap = document.querySelector<HTMLElement>('#download');
      let imgUrl = '';

      if (isAndroid()) {
        imgUrl = `/resource_images/${imgPath}/chess/imageContent.png?__static_hash__`;
        iosInstallInfo.style.visibility = 'hidden';
        torialRegion.style.display = 'none';
        downloadWrap.style.height = '100%';
        const downTips = document.querySelector<HTMLElement>('.down_tip');
        const prevBtn = document.querySelector<HTMLElement>(
          '.swiper-button-prev'
        );
        const nextBtn = document.querySelector<HTMLElement>(
          '.swiper-button-next'
        );

        if (downTips && prevBtn && nextBtn) {
          DomUtil.addClass(downTips, 'android_tip_class');
          prevBtn.style.top = '50%';
          nextBtn.style.top = '50%';
        }
      } else {
        imgUrl = `/resource_images/${imgPath}/chess/imageContent.png?__static_hash__`;

        const loadElem = document.querySelector('.load');
        const htmlString = DomUtil.create(
          `<div>
                <button disabled class="trust" id="trust" style="display: none;">一键信任</button>
            </div>`
        );
        const modalWrap = DomUtil.create<HTMLElement>(
          '<div class="modal_wrap"><div class="modal_box"><p>一键信任只支持 Safari 浏览器哦~  </p><p>请下滑查看手动信任教程。</p><button id="hideMOdal">确认</button></div></div>'
        );

        if (loadElem && htmlString) {
          loadElem.appendChild(htmlString);
        }

        if (modalWrap) {
          document.body.appendChild(modalWrap);

          modalWrap.addEventListener('click', function () {
            DomUtil.hide(modalWrap);
          });
        }
      }

      if (installTutorial) {
        // iphoneBrand.setAttribute('src', imgUrl2);
        installTutorial.setAttribute('src', imgUrl);
      }
    } catch (error) {
      uploadErrorInfo('sport.initOther', error, false);
    }
  }

  /**
   * 下载开始假的进度条
   *
   */
  let timerId: any = 0;
  let angle = 0;
  const leftContent = document.querySelector('.left-content')!;
  const rightContent = document.querySelector('.right-content')!;
  const textCircle = document.querySelector('.text-circle')!;

  function downloadProgress() {
    timerId = setInterval(function () {
      angle += 30;
      if (angle === 360) {
        reportInfoV3('ios_yabo_download_c_pv');
        downloadComplete();
        clearInterval(timerId);
        timerId = null;
      }
      if (angle > 360) {
        clearInterval(timerId);
      } else {
        if (angle > 180) {
          rightContent.setAttribute(
            'style',
            'transform: rotate(' + (angle - 180) + 'deg)'
          );
        } else {
          leftContent.setAttribute(
            'style',
            'transform: rotate(' + angle + 'deg)'
          );
        }
        textCircle.innerHTML = parseInt(String((angle * 100) / 360)) + '%';
        if (angle === 360) {
          (installBtn as any).innerText = '下载完成';
          angle = 0;
        }
      }
    }, 1666);

    const installBtn = document.querySelector<HTMLElement>('#install');
    const trustElem = document.querySelector<HTMLElement>('#trust');
    const progress = document.querySelector<HTMLElement>('#progress');
    const progressContainer =
      document.querySelector<HTMLElement>('#progressContainer');
    let timer;
    let i = 30;
    const bar = new ProgressBar.Circle(progress, {
      strokeWidth: 5,
      easing: 'linear',
      duration: 1500,
      color: '#3d72fa',
      trailColor: '#e6e1dc',
      trailWidth: 5,
      svgStyle: null,
      step: (state, circle) => {
        const value = Math.round(circle.value() * 100);
        circle.setText(value + '%');
      },
    });
    // 下载时隐藏下载完成按钮 显示进度条及信任按钮
    if (installBtn && progressContainer) {
      installBtn.style.display = 'none';
      progressContainer.style.display = 'flex';
    }
    // 如果是安卓显示正在下载
    if (isAndroid()) {
      (trustElem as any).innerText = '正在下载...';
      (installBtn as any).innerText = '正在下载...';
    }
    clearInterval(timer);
    timer = setInterval(() => {
      task();
    }, 1000);

    function task() {
      try {
        if (i <= 0) {
          bar.animate(1);
          if (isIOS()) {
            reportInfoV3('ios_yabo_download_c_pv');
          }
          setTimeout(() => {
            downloadComplete();
          }, 1500);
          clearInterval(timer);
          timer = null;
        } else {
          i--;

          if (Math.random() > 0.3 && installBtn) {
            const num = Math.floor(((30 - i) / 30) * 100);
            bar.animate(num / 100);
          }
        }
      } catch (error) {
        uploadErrorInfo('game.downloadProgress', error, false);
      }
    }
  }

  /**
   * IOS进度条读完后处理
   *
   */
  function downloadComplete() {
    try {
      // const installBtn = document.querySelector<HTMLElement>('#install');
      const confirmCompletedElem =
        document.querySelector<HTMLElement>('.confirm_completed');
      const trustElem = document.querySelector<HTMLElement>('#trust');

      // if (installBtn) {
      //   installBtn.setAttribute('disabled', 'disabled');
      //   DomUtil.addClass(installBtn, 'install_end');
      //   installBtn.innerHTML =
      //     // '<img src="/images/index/icon_dui.png"><span>下载完成</span>';
      //     `<img src="/resource_images/${imgPath}/download/icon_dui.png"><span>下载完成</span>`;
      // }

      if (confirmCompletedElem) {
        confirmCompletedElem.innerText = '安装后，需点击一键信任才可使用';
        // '请确认APP下载完成后，再点击“一键信任”';
      }

      if (trustElem) {
        DomUtil.addClass(trustElem, 'trust_active');
        trustElem.removeAttribute('disabled');
      }
    } catch (error) {
      uploadErrorInfo('sport.downloadComplete', error, false);
    }
  }

  /**
   * 展示下载的友好提示
   *
   */
  function showDownloadTips() {
    try {
      // 执行相关dom操作相关函数
      const elem = document.querySelector('.recommend-text');

      if (elem) {
        // 设置浏览器文案提示
        if (isAndroid()) {
          elem.innerHTML =
            '若无法正常安装，请使用手机自带浏览器打开<br /> （UC浏览器、Chrome谷歌浏览器）';
        } else {
          elem.innerHTML =
            '若无法正常安装，请使用手机自带浏览器打开<br />（Chrome谷歌浏览器、Safari浏览器）';
        }
      }
    } catch (error) {
      uploadErrorInfo('game.showDownloadTips', error, false);
      // 差异点
    }
  }

  /**
   * 展示ICode
   *
   */
  function showICode() {
    try {
      if (i_code) {
        // 设置i_code字段
        const iCodePanel = document.querySelector<HTMLElement>('#show_i_code');

        if (iCodePanel) {
          iCodePanel.innerText = i_code === 'nobody' ? '' : i_code;
        }
      } else if (r_code) {
        // 设置r_code字段
        const iCodePanel = document.querySelector<HTMLElement>('#show_i_code');

        if (iCodePanel) {
          iCodePanel.innerText = r_code === 'nobody' ? '' : r_code;
        }
      }
    } catch (error) {
      uploadErrorInfo('game.showICode', error, false);
      // 差异点
    }
  }

  /**
   * 初始化Swiper
   *
   */
  function initSwiper() {
    try {
      const mySwiper = new Swiper('.swiper-container', {
        pagination: {
          el: '.swiper-pagination',
        },
        navigation: {
          prevEl: '.swiper-button-prev',
          nextEl: '.swiper-button-next',
        },
      });

      const andIndexList = [
        {
          imgurl: `/resource_images/${imgPath}/chess/chessgame_an_1.png?__static_hash__`,
        },
      ];
      const iosIndexList = [
        {
          imgurl: `/resource_images/${imgPath}/chess/chessgame_ios_1.png?__static_hash__`,
        },
      ];

      let childList;

      if (isIOS()) {
        childList = iosIndexList.map(function (child) {
          return (
            '<div class="swiper-slide"> ' +
            ' <img src="' +
            child.imgurl +
            '" /></div>'
          );
        });

        onloadImage(iosIndexList);
      } else {
        childList = andIndexList.map(function (child) {
          return (
            '<div class="swiper-slide"> ' +
            ' <img src="' +
            child.imgurl +
            '" /></div>'
          );
        });
        onloadImage(andIndexList);
      }

      mySwiper.appendSlide(childList);
    } catch (error) {
      uploadErrorInfo('sport.initSwiper', error, false);
    }
  }
}
